package com.yichuang.security.quickstarts.ample.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

/**
 * <p> </p>
 *
 * @author tuonioooo
 * @site https://miliqkdoc.motopa.cn/
 * @date 2018/8/22 14:20
 */
@Configuration
@Slf4j
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public UserDetailsService users() {
        // {noop} 前缀表示跳过加密，直接将明文作为密码
        UserDetails user = User.withUsername("user")
                .password("{noop}password") // 使用 {noop} 跳过加密
                .roles("USER")
                .build();

        UserDetails admin = User.withUsername("admin")
                .password("{noop}password") // 使用 {noop} 跳过加密
                .roles("USER", "ADMIN")
                .build();

        return new InMemoryUserDetailsManager(user, admin);
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf() // 确保启用 CSRF 保护，默认开启，会自动在登录页面中加入一个 <input name="_csrf" type="hidden" value="xxxx">
                .and()
                    .authorizeRequests()
                        .anyRequest().authenticated() // 其他路径需要认证
                .and()
                    .formLogin();
//                        .loginPage("/login")
//                        .permitAll();
        return http.build();
    }

}
